package com.cn.hz.zyj.service.impl;

import com.cn.hz.zyj.helper.StringHelper;
import com.cn.hz.zyj.mapper.UserMapper;
import com.cn.hz.zyj.model.entity.UserEntity;
import com.cn.hz.zyj.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addUser(String username, String realname, String password,  String schoolId, int userType) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setRealname(realname);
        userEntity.setPwd(password);
        userEntity.setStudent_id(schoolId);
        userEntity.setUser_type(userType);

        //密码混淆项生成
        String pwdSalt = UUID.randomUUID().toString().replace("-","");
        String originPwd =password + pwdSalt;
        String pwd = StringHelper.md5(originPwd);

        long padValidDate = System.currentTimeMillis() + 7 * 24 * 3600 * 1000;

        userEntity.setPwd(pwd);
        userEntity.setPwd_salt(pwdSalt);
        userEntity.setPwd_valid_date(padValidDate);

        //初始化，默认为0
        userEntity.setPwd_error_count(0);
        userEntity.setGrade_id(0);
        userEntity.setClass_id(0);

        userMapper.addUser(userEntity);
    }

    @Override
    public Boolean login(String username, String password) {
        UserEntity user = userMapper.selectUserByUsername(username);
        if (user == null)
            return false;
        String pwd = user.getPwd();
        String pwdSalt = user.getPwd_salt();
        String inputPwd = StringHelper.md5(password+pwdSalt);
        if (inputPwd.equals(pwd)){
            redisTemplate.opsForValue().set("session_"+username,user.toString(),10, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

    @Override
    public Boolean isLogin(String username) {

        return redisTemplate.opsForValue().get("session_"+username)!=null;

    }

    @Override
    public void deleteUser(int userId) {
        userMapper.deleteUser(userId);
    }

    @Override
    public List<UserEntity> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public UserEntity findUser(int userId) {
        return userMapper.selectUser(userId);
    }



    @Override
    public void changePwd() {

    }
}
